package com.yunshipei.ui.fragment;

import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.yunshipei.common.Globals;
import com.yunshipei.common.UserLoginDataParser;
import com.yunshipei.common.manager.EnterConfig;
import com.yunshipei.common.net.HttpMethods;
import com.yunshipei.core.common.DataJSCallback;
import com.yunshipei.core.manager.TabManager;
import com.yunshipei.core.utils.SystemUtils;
import com.yunshipei.core.utils.ViewUtils;
import com.yunshipei.core.utils.YspFunUtils;
import com.yunshipei.enterplorer.R;
import com.yunshipei.enterplorer.browser.HomeWebChromeClient;
import com.yunshipei.enterplorer.browser.HomeWebView;
import com.yunshipei.enterplorer.browser.HomeWebViewClient;
import com.yunshipei.inter.JsInterface.HomeJsObject;
import com.yunshipei.manager.YspPreferences;
import com.yunshipei.model.HomeAppsBean;
import com.yunshipei.model.MainExtraBean;
import com.yunshipei.model.UserInfo;
import com.yunshipei.model.YspEvent;
import com.yunshipei.model.YspEvent.HomeFragmentEvent;
import com.yunshipei.model.YspEvent.ToolbarModelEvent;
import com.yunshipei.ui.activity.HomeExtendActivity;
import com.yunshipei.ui.activity.HomeSearchActivity;
import com.yunshipei.utils.ToastUtils;

import org.chromiun.net.ProxyChangeListener;

import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.rong.eventbus.EventBus;


public class HomeFragment extends BaseNavItemFragment implements HomeWebViewClient.HomeWebViewCallback, SwipeRefreshLayout.OnRefreshListener {

    private static final String ARGS_HOME_DATA = "com.enterplorer.home.data";

    public static final String URL_TYPE_SEARCH = "ENTERPLORER_SEARCH";
    public static final String URL_TYPE_EXTEND = "ENTERPLORER_EXTEND";
    public static final String URL_TYPE_REFRESH = "ENTERPLORER_REFRESH";

    public static final int HOME_SEARCH_REQUEST_CODE = 500;
    public static final int HOME_EXTEND_REQUEST_CODE = 501;

    @Bind(R.id.web_view_home)
    protected HomeWebView mWebView;
    @Bind(R.id.tl_home)
    protected Toolbar mToolbar;
    @Bind(R.id.home_tab_num)
    protected TextView mTvTabCount;
    @Bind(R.id.rootview)
    protected FrameLayout rootView;
    @Bind(R.id.tv_company)
    protected TextView mTvCompanyName;
    @Bind(R.id.refresh_layout)
    protected SwipeRefreshLayout mRefreshLayout;

    private Context mContext;
    private MainExtraBean mMainExtraBean;
    private String mIMEI;
    private HomeWebViewClient mWebViewClient;

    private OnFragmentInteractionListener onFragmentInteractionListener;

    public static HomeFragment newInstance(MainExtraBean mainExtraBean) {
        HomeFragment HomeFragment = new HomeFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(ARGS_HOME_DATA, mainExtraBean);
        HomeFragment.setArguments(bundle);
        return HomeFragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof HomeFragment.OnFragmentInteractionListener) {
            onFragmentInteractionListener = (OnFragmentInteractionListener) context;
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.mContext = getActivity();
        this.mMainExtraBean = (MainExtraBean) getArguments().getSerializable(ARGS_HOME_DATA);
        this.mIMEI = SystemUtils.getDevicesID(mContext);
        EventBus.getDefault().register(this);
        configYspProxy();
    }

    public void configYspProxy() {
        ProxyChangeListener.setProxyConfig(mProxyIP, mProxyPort, null, mExclusionList);
    }

    @SuppressLint({"SetJavaScriptEnabled", "AddJavascriptInterface"})
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_webview, container, false);
        ButterKnife.bind(this, view);

        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mToolbar.setBackgroundColor(EnterConfig.getInstance().getGlobalColor());
        mTvTabCount.setTextColor(EnterConfig.getInstance().getGlobalColor());
        if (mMainExtraBean == null) {
            mMainExtraBean = (MainExtraBean) getArguments().getSerializable(ARGS_HOME_DATA);
        }
      //  mTvCompanyName.setText(mMainExtraBean.getCompanyTitle());
       mTvCompanyName.setText("中可OA");
        updateTabCount();
        ViewTreeObserver observer = rootView.getViewTreeObserver();
        observer.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                rootView.getViewTreeObserver().removeOnPreDrawListener(this);
                int height = mToolbar.getHeight();
                mWebView.setToolbarHeight(height);
                return true;
            }
        });
        String loadUrl;
        String onLineUrl = mMainExtraBean.getOnLineHome();
        if (!TextUtils.isEmpty(onLineUrl)) {
            loadUrl = onLineUrl;
        } else {
            loadUrl = "file://" + mContext.getFilesDir().getPath() + File.separator + Globals.APP_WEB_ROOT_PATH + File.separator + mMainExtraBean.getHomeResDir() + File.separator + "index.html";
        }
        mWebView.addJavascriptInterface(new HomeJsObject(getActivity()), Globals.JS_OBJECT_ENTERPLORER_HOME);
        mWebViewClient = new HomeWebViewClient(mContext, loadUrl, mWebView, this);
        mWebView.setWebViewClient(mWebViewClient);
        mWebView.setWebChromeClient(new HomeWebChromeClient(mWebView));
        ProxyChangeListener.sendProxyReceiver(mContext);
        mWebView.loadUrl(loadUrl);
        mRefreshLayout.setOnRefreshListener(this);
        mRefreshLayout.setProgressViewOffset(true, 0, getResources().getDimensionPixelOffset(R.dimen.swep_refresh_position));
        mRefreshLayout.setColorSchemeColors(EnterConfig.getInstance().getGlobalColor());
        int managerCode = mMainExtraBean.getManagerCode();
        mRefreshLayout.setEnabled(managerCode >= 1);





        }

    @Override
    public void onRefresh() {
        mRefreshLayout.setEnabled(false);
        UserInfo userInfo = mMainExtraBean.getUserInfo();
        YspFunUtils.updateXCloudData(mContext, userInfo.getUuid(), userInfo.getCompanyId(), new DataJSCallback() {
            @Override
            public void error(String errorMsg) {
                mRefreshLayout.setRefreshing(false);
                mRefreshLayout.setEnabled(true);
                ToastUtils.showToast(errorMsg);
            }

            @SuppressLint("ApplySharedPref")
            @Override
            public void success(String result) {
                List<HomeAppsBean> homeApps = new UserLoginDataParser(getActivity()).dataJS2HomeApps(result);
                EventBus.getDefault().post(new YspEvent.UpdateHomeApps(homeApps));
                YspPreferences.getInstance().getSharedPreferences().edit().putString(Globals.YSP_DATA_JS, result).commit();
                mWebView.reload();
                mRefreshLayout.setRefreshing(false);
                mRefreshLayout.setEnabled(true);
            }
        });
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        final AMapLocationClient aMapLocationClient = new AMapLocationClient(mContext.getApplicationContext());
        aMapLocationClient.setLocationListener(new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                if (aMapLocation != null && aMapLocation.getErrorCode() == 0) {
                    String district = aMapLocation.getDistrict();
                    String temp = TextUtils.isEmpty(district) ? "北京" : district.substring(0, district.length() - 1);
                    mWebViewClient.setLocation(temp);
                    if (mWebView != null) {
                        mWebView.loadUrl("javascript:setLocation(\"" + temp + "\")");
                    }
                    String address = aMapLocation.getAddress();
                    HttpMethods.getInstance().sendLocation(mIMEI, TextUtils.isEmpty(address) ? "北京" : address);
                }
                aMapLocationClient.onDestroy();
            }
        });
        AMapLocationClientOption aMapLocationClientOption = new AMapLocationClientOption();
        aMapLocationClientOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        aMapLocationClientOption.setOnceLocation(true);
        aMapLocationClientOption.setHttpTimeOut(20000);
        aMapLocationClient.setLocationOption(aMapLocationClientOption);
        aMapLocationClient.startLocation();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    public void onEventMainThread(HomeFragmentEvent event) {
        String url = "file://" + mContext.getFilesDir().getPath() + File.separator + Globals.APP_WEB_ROOT_PATH + File.separator + mMainExtraBean.getHomeResDir() + File.separator + event.getUrl();
        if (URL_TYPE_SEARCH.equals(event.getType())) {
            Intent intent = new HomeSearchActivity.HomeSearchIntentBuilder(getActivity()).setURL(url).getIntent();
            startActivityForResult(intent, HOME_SEARCH_REQUEST_CODE);
        } else if (URL_TYPE_EXTEND.equals(event.getType())) {
            Intent intent = new HomeExtendActivity.HomeExtendIntentBuilder(getActivity()).setTitle(event.getTitle()).setUrl(url).getIntent();
            startActivityForResult(intent, HOME_EXTEND_REQUEST_CODE);
        } else if (URL_TYPE_REFRESH.equals(event.getType())) {
            mWebView.reload();
        }
    }

    //从BrowserFragment切换到HomeFragment需要重新设置crosswalk的代理
    public void onEventMainThread(YspEvent.ConfigProxy configProxy) {
        configYspProxy();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (mWebView != null) {
            mWebView.onDestroy();
            mWebView = null;
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        onFragmentInteractionListener = null;
    }

    //更新toolBar上的数字
    public void updateTabCount() {
        int size = TabManager.getInstance().getSize() + 1;
        mTvTabCount.setText(String.valueOf(size));
    }

    //跟新首页标签数目
    public void onEventMainThread(YspEvent.UpdateTabCount event) {
        updateTabCount();
    }

    @OnClick({R.id.fl_label_view, R.id.iv_qr_code})
    public void onClickEvent(View view) {
        switch (view.getId()) {
            case R.id.fl_label_view:
                onFragmentInteractionListener.onDrawerOpen();
                break;
            case R.id.iv_qr_code:
                onFragmentInteractionListener.openQRCode();
                break;
        }
    }

    private void hideToolbarAnim() {
        ObjectAnimator.ofFloat(mToolbar, "translationY", mToolbar.getTranslationY(), -mToolbar.getHeight()).start();
    }

    private void showToolbarAnim() {
        ObjectAnimator.ofFloat(mToolbar, "translationY", mToolbar.getTranslationY(), 0).start();
    }

    public void onEventMainThread(ToolbarModelEvent event) {
        if (event.isShouldShow()) {
            showToolbarAnim();
        } else {
            hideToolbarAnim();
        }
    }

    public void refresh() {
        if (mWebView != null) {
            mWebView.reload();
        }
    }

    private String webviewFileName = "";

    public String getHomeWebViewCaptureURL(boolean webViewVisible) {
        if (webViewVisible) {
            TextureView textureView = ViewUtils.findXWalkTextureView(mWebView);
            if (textureView != null) {
                Bitmap bitmap = textureView.getBitmap();
                int toolBar = mContext.getResources().getDimensionPixelSize(R.dimen.title_bar_height);
                bitmap = Bitmap.createBitmap(bitmap, 0, toolBar, mWebView.getWidth(), mWebView.getHeight() - toolBar);
                try {
                    webviewFileName = mContext.getCacheDir() + File.separator + System.currentTimeMillis() + ".jpg";
                    FileOutputStream fos = new FileOutputStream(webviewFileName);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 7, fos);
                    fos.close();
                    bitmap.recycle();
                    return webviewFileName;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return webviewFileName;
    }

    @Override
    public void handleAppUrl(String url) {
        onFragmentInteractionListener.openWebApp(url);
    }

    public interface OnFragmentInteractionListener {
        void onDrawerOpen();

        void openWebApp(String url);

        void openQRCode();
    }
}
